﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ChairtyBank.DAL;

namespace ChairtyBank
{
    public partial class CustomerForm : Form
    {
        public CustomerForm()
        {
            InitializeComponent();

        }
        private static bool saveFlag = true;
        private bool restFlag = false;
        private bool lastInsFlag = false;
        private Int32 clientID = 0;
        private Int32 ProjectId = 0;
        private Int32 loanId = 0;

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.CustomerGrp.Visible = true;
            this.CustomerGrp.Enabled = true;
            this.linkProject.Visible = true;

            cleanAllFields();


        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {

            saveFlag = true;
            if (idTxt.Text == "" || idTxt.Text.Equals(null) || txtLoanValue.Text == "" || txtLoanValue.Text.Equals(null) || txtInstalmentAmount.Text == "" || txtInstalmentAmount.Equals(null))
                MessageBox.Show("يجب إدخال كل البيانات");
            else
            {
                if (CustomerGrp.Enabled == true && saveFlag)
                    clientID = addClientValues();
                if (projectGrp.Enabled == true && projectGrp.Visible == true && saveFlag)
                    ProjectId = addProjectValues();
                if (saveFlag && LoanGrp.Visible != false && addLoanValues(clientID, ProjectId))
                {
                    MessageBox.Show("تم حفظ البيان");
                }
                else
                    MessageBox.Show("بيانات غبر صحيحة");
            }


        }



        private void CustomerForm_Load(object sender, EventArgs e)
        {
            LoadAkhesa2yComboBox();
            
        
        }

        private void LoadAkhesa2yComboBox() {
            AKHESA2Y.Items.Clear();
            List<AkhesEntity> AList = Akhes.GetAll();
            foreach (AkhesEntity A in AList)
                AKHESA2Y.Items.Add(A.name);
        }

        private Int32 addClientValues()
        {
            ClientEntity client = fillClientEntityFromForm();
            if (Client.Add(client))
            {
                client.Id =client.Id;
                CustomerGrp.Enabled = false;
            }
            else
                saveFlag = false;

            return client.Id;

        }

        private Int32 addProjectValues()
        {
            ProjectEntity project = fillProjectEntityFromForm();
            project.Id = Project.Add(project);
            if (project.Id > 0)
                projectGrp.Enabled = false;
            else
                saveFlag = false;
            return project.Id;
        }

        private bool addLoanValues(Int32 clientID, Int32 projectID)
        {
            //TODO see here 
            txtRest.Text = txtLoanValue.Text;
            if (!Loan.Add(fillLoanEntityFromForm()))
              return false;
            AddInstalmentForm(Loan.GetLoan(clientID,projectID));
            LoanGrp.Enabled = false;
            return true;
        }



        private void AddInstalmentForm(LoanEntity le) {
            InstalmentEntity I = new InstalmentEntity();
            Int32 lastInst = 0;
            try
            {
                lastInst = Int32.Parse(txtLastInst.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("خطأ في قيمة أخر قسط");
                throw ex;
            }
           // le.Instalment_amount = le.Rest / le.Instalment_amount;
            I.Loan_ID = le.Id;
            for (int i = 0; i < le.Period; i++) {
                I.Notes = "";
                I.payed = false;
                I.Penalty = 0;
                I.Total = le.Instalment_amount;
                I.Amount = le.Instalment_amount;
                I.userId = 1;
                I.Payed_Amount = 0;
                I.Rest = le.Rest;
                if (this.comEvery.Text == "شهر")  
                    I.DueDate = le.StartDate.AddMonths(1*i); 
                else
                    I.DueDate = le.StartDate.AddDays(7*i);
                if (i == le.Period-1)
                {
                    le.EndDate = I.DueDate;
                    I.Amount=(this.restFlag? le.Rest%le.Instalment_amount : le.Instalment_amount);
                    if (this.lastInsFlag)
                    {
                        I.Amount = Int32.Parse(txtLastInst.Text);
                    }
                    I.Total = I.Amount;
                    Loan.Update(le);

                }
                Instalment.Add(I);
                

            }
          
        }
        private void CreateNewInstForSchedule(LoanEntity le)
        {
            InstalmentEntity I = new InstalmentEntity();
            // le.Instalment_amount = le.Rest / le.Instalment_amount;
            I.Loan_ID = le.Id;
            for (int i = 0; i < le.Period; i++)
            {
                I.Notes = "";
                I.payed = false; 
                I.Penalty = 0;
                I.Total = le.Instalment_amount;
                I.Amount = le.Instalment_amount;
                I.userId = 1;
                I.Payed_Amount = 0;
                I.Rest = le.Rest;
                if (this.comEvery.Text == "شهر")
                    I.DueDate = le.StartDate.AddMonths(1 * i);
                else
                    I.DueDate = le.StartDate.AddDays(7 * i);
                if (i == le.Period - 1)
                {
                    le.EndDate = I.DueDate;
                    I.Amount = (this.restFlag ? le.Rest % le.Instalment_amount : le.Instalment_amount);
                    if (this.lastInsFlag)
                        I.Amount = Int32.Parse(txtLastInst.Text);
                    I.Total = I.Amount;
                    Loan.Update(le);
                }
                Instalment.Add(I);


            }

        }


        private ClientEntity fillClientEntityFromForm() {
            ClientEntity client = new ClientEntity();
            client.Id = Int32.Parse(idTxt.Text);
            client.Name = nameTxt.Text;
            client.Job = jobTxt.Text;
            client.Phone = phoneTxt.Text;
            //client.DateOfBirth = DOBpicr.Value;
            client.Address = addressTxt.Text;
            client.Akhesaye = AKHESA2Y.Text;
            client.Round = Int32.Parse(txtRound.Text); 
            return client;
        }


        private ProjectEntity fillProjectEntityFromForm()
        {
            ProjectEntity project = new ProjectEntity();
            project.Place = placeTxt.Text;
            project.Title = titleTxt.Text;
            project.Id = ProjectId;
            if (radioEntagy.Checked)
                project.Type = "إنتاجى";
            if (radioKhadmy.Checked)
                project.Type = "خدمى";
            if (radioTogary.Checked)
                project.Type = "تجارى";

            if (radioNew.Checked)
                project.Establish = "جديد";
            if (radioSupported.Checked)
                project.Establish = "قائم/تم دعمه";

            return project;
        }
                
        private LoanEntity fillLoanEntityFromForm() {
            Int32 lastInst = 0;
            Int32 LoanValue = (Int32.Parse(txtRest.Text));
            try
            {
                lastInst = Int32.Parse(txtLastInst.Text);
            }
            catch (Exception ex) 
            {
                MessageBox.Show("خطأ في قيمة أخر قسط");
                throw ex;
            }

            if (lastInst > 0)
            {
                this.lastInsFlag = true;
            }
            Int32 numOfIns= LoanValue / (Int32.Parse(txtInstalmentAmount.Text));
            if((LoanValue % Int32.Parse(txtInstalmentAmount.Text)) != 0) 
            {
                if (!lastInsFlag)
                {
                    numOfIns++;
                }

                this.restFlag=true;
            }
            txtperiod.Text = numOfIns.ToString();
            LoanEntity l = new LoanEntity();
            l.Customer_Id = clientID;
            l.Project_ID = ProjectId;
            l.Period = numOfIns;
            l.Instalment_every = comEvery.Text; 
            l.Value = Int32.Parse(txtLoanValue.Text);
            l.Instalment_amount = Int32.Parse(txtInstalmentAmount.Text);
            l.StartDate = startDatepkr.Value.Date;
            l.Rest = Int32.Parse(txtRest.Text);
            l.EndDate = startDatepkr.Value.Date;
            l.PayDate = endDatepkr.Value.Date;
            l.Id = loanId;

            return l;
        }
        

        private void cleanAllFields()
        {
            clientID = 0;
            ProjectId = 0;
            loanId = 0;

            this.nameTxt.Text = "";
            this.phoneTxt.Text = "";
            this.addressTxt.Text = "";
            this.idTxt.Text = "";
            this.jobTxt.Text = "";
            this.placeTxt.Text = "";
            this.titleTxt.Text = "";
            this.comEvery.Text = "";
            this.txtInstalmentAmount.Text = "";
            this.txtLoanValue.Text = "";
            this.txtperiod.Text = "";
            this.AKHESA2Y.Text = "";
            this.txtRest.Text = "";
            this.txtRound.Text = "";
            this.startDatepkr.Value = DateTime.Now;

        }


        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.projectGrp.Visible = true;
            this.projectGrp.Enabled = true;

            this.LoanGrp.Visible = true;
            this.LoanGrp.Enabled = true;

        }


        private void toolStripButton3_Click(object sender, EventArgs e)
        {

            if (nameTxt.Text != "" && !nameTxt.Equals(null))
            {
                List<ClientEntity> c = Client.GetClients("%" + nameTxt.Text + "%");
                if (c.Count == 0)
                    MessageBox.Show("هذا العميل غير موجود");
                else if (c.Count == 1)
                    publishClientValues(c[0]);
                else
                    showGridView(c);
            }
        }

        
        public void publishClientValues(ClientEntity ce)
        {
            clientID = ce.Id;
            this.nameTxt.Text = ce.Name;
            this.phoneTxt.Text = ce.Phone;
            this.addressTxt.Text = ce.Address;
            this.idTxt.Text = ce.Id.ToString();
            this.jobTxt.Text = ce.Job;
            //this.DOBpicr.Value = ce.DateOfBirth;
            this.AKHESA2Y.Text = ce.Akhesaye;
            this.txtRound.Text = ce.Round.ToString();
            getLoanAndProjectDetails(clientID);
           
            CustomerGrp.Enabled = false;
            projectGrp.Enabled = false;
            LoanGrp.Enabled = false;
        }

        private void publishProjectValues(ProjectEntity pe)
        {
            ProjectId = pe.Id;
            placeTxt.Text = pe.Place;
            titleTxt.Text = pe.Title;

            if (pe.Type == "إنتاجى")
                radioEntagy.Select();
            else if (pe.Type == "خدمى")
                radioKhadmy.Select();
            else if (pe.Type == "تجارى")
                radioTogary.Select();

            if (pe.Establish == "جديد")
                radioNew.Select();
            else if (pe.Establish == "قائم/تم دعمه")
                radioSupported.Select();

        }
        
        private void publishLoanValues(LoanEntity l)
        {
            loanId = l.Id;
            txtperiod.Text = l.Period.ToString();
            txtInstalmentAmount.Text = l.Instalment_amount.ToString();
            comEvery.Text = l.Instalment_every;
            txtLoanValue.Text = l.Value.ToString();
            endDatepkr.Value = l.PayDate;
            startDatepkr.Value = l.StartDate;
           txtRest.Text = l.Rest.ToString();

        }
        
        private void showGridView(List<ClientEntity> lc)
        {
            CustomerSearchForm dialogue = new CustomerSearchForm();
            dialogue.customerDataGrid.DataSource = lc;
            dialogue.currentForm = 0;
            dialogue.ShowDialog(this);

            //customerDataGrid.DataSource = lc;
            //customerDataGrid.Visible = true;
            //groupBox1.Visible = true;
        }
        
        private void getLoanAndProjectDetails(Int32 clientID)
        {
            try { 
            LoanEntity le = Loan.GetLoan(clientID);
            if (!le.Equals(null))
            {
                publishLoanValues(le);
                ProjectEntity pe = Project.GetProject(le.Project_ID);
                publishProjectValues(pe);
                projectGrp.Visible = true;
                LoanGrp.Visible = true;
            }

            }catch{}

        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            Reschedule();

        }
         
        private void DeleteBVuttun_Click(object sender, EventArgs e)
        {
            if (idTxt.Text != "" && !idTxt.Text.Equals(null) )
            {
                DialogResult result = MessageBox.Show("هل تريد حذف " + nameTxt.Text + "؟ ", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    try
                    {
                        Client.Delete(Int32.Parse(idTxt.Text));
                        Project.Delete(fillProjectEntityFromForm());
                        CNotes.Delete(Int32.Parse(idTxt.Text));
                        cleanAllFields();
                        MessageBox.Show("تم حذف العميل");
                    }
                    catch {
                        MessageBox.Show("حدث خطأ فى الحذف");
                    }

                }
            }
            else
                MessageBox.Show("بعض البيانات غبر موجودة");

        }

        
        
        private void Reschedule() {
           if (txtInstalmentAmount.Enabled == false)
            {
                txtInstalmentAmount.Parent.Enabled = true;
                saveButton.Enabled = false;
                updateButton.Enabled = false;
                //endDatepkr.Enabled = false;
                toolStripButton4.Text = "إعادة جدولة";
            }
            else {
                strorePrevInstalment();
                generateNewSchedule();
                MessageBox.Show("تم إعادة الجدولة");
                this.LoanGrp.Enabled = false;
                saveButton.Enabled = true;
                updateButton.Enabled = true;                
            }

        }

        private void strorePrevInstalment() {
            //TODO to be tested
            List<InstalmentEntity> list = Instalment.GetInstalment(loanId);

            foreach (InstalmentEntity I in list)
            {
                if (I.payed == true)
                {
                     I.Notes += "تمت إعادة الجدولة في"+DateTime.Now.ToShortDateString();
                    Backup.Add(I, clientID ,nameTxt.Text, titleTxt.Text);
                    Instalment.Update(I);
                } else {
                    Instalment.Delete(I);
                }
                
            }
        }
        
        private void generateNewSchedule() {
          LoanEntity le = fillLoanEntityFromForm();
          AddInstalmentForm(le);

        }

        private void nameTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                
                List<ClientEntity> c = Client.GetClients("%" + nameTxt.Text + "%");
                if (c.Count == 0)
                    MessageBox.Show("هذا العميل غير موجود");
                else if (c.Count == 1)
                    publishClientValues(c[0]);
                else
                    showGridView(c);
            }

        }

        private void idTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13&& idTxt.Text!="")
            {
                
                ClientEntity c = Client.GetClient(Int32.Parse(idTxt.Text));
                if (c==null|| c.Equals(null))
                    MessageBox.Show("هذا العميل غير موجود");
                else 
                    publishClientValues(c);
               
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Akhes.Add(AKHESA2Y.Text);
            AKHESA2Y.Text = "";
            LoadAkhesa2yComboBox();
        }

  

        private void button3_Click(object sender, EventArgs e)
        {
            Akhes.Delete(AKHESA2Y.SelectedItem.ToString());
            AKHESA2Y.Text = "";
            LoadAkhesa2yComboBox();
        }

        private void idTxt_TextChanged(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            if (idTxt.Text!="")
            {
                
                ClientEntity ce = Client.GetClient(Int32.Parse(idTxt.Text));
                if (ce == null || ce.Equals(null))
                    MessageBox.Show("هذا العميل غير موجود");
                else
                {
                    clientID = ce.Id;
                    this.nameTxt.Text = ce.Name;
                    this.phoneTxt.Text = ce.Phone;
                    this.addressTxt.Text = ce.Address;
                    this.idTxt.Text = ce.Id.ToString();
                    this.jobTxt.Text = ce.Job;
                    this.AKHESA2Y.Text = ce.Akhesaye;
                    this.txtRound.Text = ce.Round.ToString();


                    CustomerGrp.Enabled = false;
                    projectGrp.Enabled = true;
                    LoanGrp.Enabled = true;
                }
            
            

        }

        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            if (CustomerGrp.Enabled == false && projectGrp.Enabled == false)
            {
                CustomerGrp.Enabled = true;
                projectGrp.Enabled = true;
            }
            else
            {
                Client.Update(fillClientEntityFromForm());
                Project.Update(fillProjectEntityFromForm());
                CustomerGrp.Enabled = false;
                projectGrp.Enabled = false;
                MessageBox.Show("تم تعديل البيانات");
            }


        }

        private void label22_Click(object sender, EventArgs e)
        {

        }

        private void txtLastInst_TextChanged(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {
        }
    }
}
